import os
import logging
from dotenv import load_dotenv
from wechatpy import WeChatClient
from wechatpy.exceptions import WeChatClientException
from sqlalchemy.orm import Session
from datetime import datetime

from commons.database import Database
from DAL.user import User
from DAL.order import Order

# 加载环境变量
load_dotenv()

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# 初始化微信客户端
WECHAT_APPID = os.getenv('WECHAT_APPID')
WECHAT_SECRET = os.getenv('WECHAT_SECRET')

client = WeChatClient(WECHAT_APPID, WECHAT_SECRET)

class WeChatNotificationService:
    """微信通知服务类，处理各类模板消息发送"""

    ORDER_STATUS_TEMPLATE_ID = 'your_order_status_template_id'  # 需要替换为实际的模板ID
    PAYMENT_SUCCESS_TEMPLATE_ID = 'your_payment_success_template_id'  # 需要替换为实际的模板ID

    @staticmethod
    def get_user_openid(user_id: int) -> str:
        """获取用户的openid"""
        db: Session = next(Database.get_db())
        try:
            user = db.query(User).filter(User.id == user_id).first()
            if user and user.openid:
                return user.openid
            logger.warning(f"用户 {user_id} 未找到或未绑定openid")
            return None
        finally:
            db.close()

    @staticmethod
    def send_order_status_notification(order_id: int, user_id: int, status: int):
        """
        发送订单状态变更通知
        status: 0-待付款, 1-已付款, 2-已发货, 3-已完成, 4-已取消
        """
        openid = WeChatNotificationService.get_user_openid(user_id)
        if not openid:
            return False

        # 获取订单信息
        db: Session = next(Database.get_db())
        try:
            order = db.query(Order).filter(Order.id == order_id).first()
            if not order:
                logger.warning(f"订单 {order_id} 不存在")
                return False
        finally:
            db.close()

        # 订单状态描述
        status_descriptions = {
            0: "待付款",
            1: "已付款",
            2: "已发货",
            3: "已完成",
            4: "已取消"
        }
        status_text = status_descriptions.get(status, "未知状态")

        # 模板消息数据
        data = {
            "first": {"value": f"您的订单状态已更新为：{status_text}"},
            "keyword1": {"value": f"#{order_id}"},
            "keyword2": {"value": datetime.now().strftime("%Y-%m-%d %H:%M:%S")},
            "keyword3": {"value": f"¥{order.total_amount:.2f}"},
            "remark": {"value": "请及时查看订单详情并进行后续操作。"}
        }

        try:
            response = client.message.template_send(
                touser=openid,
                template_id=WeChatNotificationService.ORDER_STATUS_TEMPLATE_ID,
                data=data,
                url=f"pages/order/detail?id={order_id}"  # 点击跳转的小程序页面
            )
            if response.get('errcode') == 0:
                logger.info(f"订单 {order_id} 状态通知发送成功")
                return True
            else:
                logger.error(f"订单 {order_id} 状态通知发送失败: {response}")
                return False
        except WeChatClientException as e:
            logger.error(f"微信API调用失败: {str(e)}")
            return False

    @staticmethod
    def send_payment_success_notification(order_id: int, seller_id: int):
        """向卖家发送订单支付成功通知"""
        openid = WeChatNotificationService.get_user_openid(seller_id)
        if not openid:
            return False

        # 获取订单信息
        db: Session = next(Database.get_db())
        try:
            order = db.query(Order).filter(Order.id == order_id).first()
            if not order:
                logger.warning(f"订单 {order_id} 不存在")
                return False
        finally:
            db.close()

        # 模板消息数据
        data = {
            "first": {"value": "您有一笔新的订单已支付成功"},
            "keyword1": {"value": f"#{order_id}"},
            "keyword2": {"value": datetime.now().strftime("%Y-%m-%d %H:%M:%S")},
            "keyword3": {"value": f"¥{order.total_amount:.2f}"},
            "remark": {"value": "请及时处理订单并发货。"}
        }

        try:
            response = client.message.template_send(
                touser=openid,
                template_id=WeChatNotificationService.PAYMENT_SUCCESS_TEMPLATE_ID,
                data=data,
                url=f"pages/seller/order/detail?id={order_id}"  # 卖家订单详情页
            )
            if response.get('errcode') == 0:
                logger.info(f"卖家订单 {order_id} 支付成功通知发送成功")
                return True
            else:
                logger.error(f"卖家订单 {order_id} 支付成功通知发送失败: {response}")
                return False
        except WeChatClientException as e:
            logger.error(f"微信API调用失败: {str(e)}")
            return False

# 创建服务实例
wechat_service = WeChatNotificationService()